package com.xhb;

import static com.teamdev.jxbrowser.engine.RenderingMode.HARDWARE_ACCELERATED;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

import org.noear.solon.Solon;
import org.noear.solon.boot.jlhttp.HTTPServer;
import org.noear.solon.core.util.PathUtil;
import org.noear.solon.extend.feign.EnableFeignClient;
import org.noear.solon.schedule.annotation.EnableScheduling;

import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.engine.EngineOptions;
import com.teamdev.jxbrowser.engine.ProprietaryFeature;
import com.xhb.biz.job.UserDataSyncJob;
import com.xhb.ui.Tab;
import com.xhb.ui.TabButton;
import com.xhb.ui.TabFactory;
import com.xhb.ui.TabbedPane;
import com.xhb.ui.download.BottomDownloadBar;
import com.xhb.ui.http.HttpServer;
import com.xhb.ui.keys.ShortcutHandle;
import com.xhb.ui.proxy.ProxyManager;
import com.xhb.ui.resources.Resources;
import com.xhb.ui.tools.LogFormat;

@EnableScheduling
@EnableFeignClient
public class EasyBrowserApplication {

	/**
	 * 考试模式
	 */
	public static boolean examMode = false;

	/**
	 * 最大化
	 */
	private static final int BIG = 6;


	public static TabbedPane tabbedPane;

	public static ShortcutHandle shortcutHandle;

	private static JFrame frame;

	private static void initEnvironment() throws Exception {
		System.setProperty("jxbrowser.license.key",
				"6P835FT5HAPTB03TPIEFPGU5ECGJN8GMGDD79MD7Y52NVP0K0IV6FHYZVQI25H0MLGI2");
//        System.setProperty("apple.laf.useScreenMenuBar", "true");
		/* System.setProperty( "sun.java2d.uiScale", "1.0" ); */
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		JPopupMenu.setDefaultLightWeightPopupEnabled(false);
	}

	public static void main(String[] args) throws Exception {

		// Creates Browser instance with context configured to use specified proxy
		// settings.
		initEnvironment();
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					LogFormat.init();
					new HttpServer().createServer();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		Solon.start(EasyBrowserApplication.class, args);
		// 异步跑一次用户数据同步定时任务
		CompletableFuture.runAsync(() -> {
			Solon.context().getBeanAsync(UserDataSyncJob.class, UserDataSyncJob::run);
		});
		// 初始化代理配置
		afterLoad();
		SwingUtilities.invokeLater(() -> {
//			loading.setVisible(false);
//			loading.dispose();
			initAndDisplayUI();
		});
	}

	private static void initAndDisplayUI() {
		frame = new JFrame(Solon.cfg().get("easy-borwser.name"));
		tabbedPane = new TabbedPane();
		shortcutHandle = new ShortcutHandle(tabbedPane, frame);
		shortcutHandle.regShortcutKeys();
		System.setProperty("com.apple.mrj.application.apple.menu.about.name", Solon.cfg().get("easy-borwser.name"));
		
		EngineOptions options = EngineOptions.newBuilder(HARDWARE_ACCELERATED).userDataDir(Paths.get(HttpServer.BASE_PATH+"/p/"+UUID.randomUUID().toString()))
				.enableProprietaryFeature(ProprietaryFeature.AAC).enableProprietaryFeature(ProprietaryFeature.H_264)
				.enableProprietaryFeature(ProprietaryFeature.WIDEVINE)
				.addSwitch("--remote-allow-origins=http://127.0.0.1:9222  --allow-file-access-from-files").remoteDebuggingPort(9222).enableIncognito().disableWebSecurity().
				allowFileAccessFromFiles()
				.build();
		Engine engine = Engine.newInstance(options);
		Tab tab = TabFactory.createTab(Solon.cfg().get("easy-borwser.default-index"), engine.newBrowser());
		insertTab(tab);
		insertNewTabButton(tabbedPane);

		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				tabbedPane.disposeAllTabs();
				System.exit(0);
			}
		});
		frame.add(tabbedPane, BorderLayout.CENTER);
		frame.add(BottomDownloadBar.getInstance(), BorderLayout.SOUTH);
		BottomDownloadBar.getInstance().close();

		frame.setSize(1024, 700);
		
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		
		frame.setLocationRelativeTo(null);
		frame.setIconImage(Resources.getIcon("logo.png").getImage());
		frame.setVisible(true);

		// 不支持最小化
		if (examMode) {
			// 永远最大化，并且在最前面，无法切屏,无法调整大小
			frame.setExtendedState(BIG);
			frame.setAlwaysOnTop(true);
			frame.setResizable(false);
			frame.addWindowStateListener(new WindowStateListener() { // 状态监听器
				public void windowStateChanged(WindowEvent e) {
					if (e.getNewState() != BIG) {
						frame.setExtendedState(BIG);
					}
				}
			});
		}
	}

	/**
	 * 在非考试模式下，添加新tab按钮
	 *
	 * @param tabbedPane
	 */
	private static void insertNewTabButton(final TabbedPane tabbedPane) {
		// 没有开启考试模式的时候才可以new-tab
		if (!examMode) {
			TabButton button = new TabButton(Resources.getIcon("new-tab.png"), "New tab");
			button.addActionListener(new ActionListener() {
				public void actionPerformed(final ActionEvent e) {
					
					
					EngineOptions options = EngineOptions.newBuilder(HARDWARE_ACCELERATED).userDataDir(Paths.get(HttpServer.BASE_PATH+"/p/"+UUID.randomUUID().toString()))
							.enableProprietaryFeature(ProprietaryFeature.AAC).enableProprietaryFeature(ProprietaryFeature.H_264)
							.enableProprietaryFeature(ProprietaryFeature.WIDEVINE)
							.addSwitch("--remote-allow-origins=http://127.0.0.1:9222  --allow-file-access-from-files").remoteDebuggingPort(9222).enableIncognito().disableWebSecurity().
							allowFileAccessFromFiles()
							.build();
					Engine engine = Engine.newInstance(options);
					
					insertTab(TabFactory.createTab(Solon.cfg().get("easy-borwser.default-index"), engine.newBrowser()));
				}
			});
			tabbedPane.addTabButton(button);
		}
	}

	public static void insertTab(Tab tab) {
		tabbedPane.addTab(tab);
		tabbedPane.selectTab(tab);
	}

	public static void afterLoad() {
		ProxyManager.loadSettings();
	}

	public static ShortcutHandle getShortcutHandle() {
		return shortcutHandle;
	}

	
	public static TabbedPane getTabbedPane() {
		return tabbedPane;
	}

	public static JFrame getFrame() {
		return frame;
	}
}
